package org.youyun56.gpsserver.command;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.youyun56.gpsserver.command.console.ConsoleCommand;
import org.youyun56.gpsserver.command.console.SocketCommand;

public class CommandAssigner {

    private static Logger logger = LoggerFactory.getLogger(CommandAssigner.class);

    private static List<ConsoleCommand> box = new ArrayList<ConsoleCommand>();

    private static class CommandAssignerSingletonHolder {
        private static final CommandAssigner INSTANCE = new CommandAssigner();
    }

    public static CommandAssigner getInstance() {
        return CommandAssignerSingletonHolder.INSTANCE;
    }

    private CommandAssigner() {
    }

    public void registerCommand(ConsoleCommand c) {
        int size = box.size();
        for (int i = 0; i < size; i++) {
            if (box.get(i).equals(c)) {
                box.set(i, c);
                return;
            }
        }
        box.add(c);
    }

    /*
     * 功能描述：注销命令 参数：命令对象Command c
     */
    synchronized public void removeCommand(Command c) {
        int size = box.size();
        for (int i = 0; i < size; i++) {
            if (box.get(i).equals(c)) {
                box.remove(i);
                return;
            }
        }
    }

    public Object assign(SocketCommand sc) {
        String txt = sc.getCommandLine();
        if (txt.trim().equals("")) {
            return GlobalProperties.NEWLINE;
        }
        int size = box.size();
        for (int i = 0; i < size; i++) {
            ConsoleCommand c = box.get(i);
            Pattern p = Pattern.compile(c.getRegExp());
            Matcher m = p.matcher(txt);
            if (m.matches()) {
                try {
                    c.setInput(txt);
                    return c.execute();
                }
                catch (Exception e) {
                    logger.error("error occour when execute commond:" + sc.getCommand(), e);
                    return e.toString() + GlobalProperties.NEWLINE;
                }
            } else {
                // System.out.println(p+" not match "+txt);
            }
        }
        return "ERROR COMMAND : " + txt + " , PRINT 'help' FOR HELP ." + GlobalProperties.NEWLINE;
    }

    public List<ConsoleCommand> getAllCommands() {
        return box;
    }

    public void clearCommand() {
        box.clear();
    }

    public ConsoleCommand findCommand(String command) {
        // TODO Auto-generated method stub
        return null;
    }

}
